package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.widget.layout.SettingBar;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.LinkageNewBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.LinkageDataHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class AirQualityActivityNew extends AppActivity {
    private SettingBar settingAction;
    private SettingBar settingReferenceArea;
    private SettingBar settingDataSourceDevice;
    private SettingBar settingLinkageAction;
    private TextView tvAirQuality;
    private RadioGroup whenRadioGroup;
    private String deviceName;
    private LinkageNewBean mLinkageBean;
    private LinkageNewBean.LinkageDeviceCondition mLinkageCondition;
    private BottomListDialog mBottomActionDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_air_quality_new;
    }

    @Override
    protected void initView() {
        mLinkageCondition =  getSerializable("condition");
        settingAction = findViewById(R.id.setting_action);
        settingReferenceArea = findViewById(R.id.setting_reference_area);
        settingDataSourceDevice = findViewById(R.id.setting_data_source_device);
        settingLinkageAction = findViewById(R.id.setting_linkage_action);
        tvAirQuality = findViewById(R.id.tv_air_quality);
        whenRadioGroup = findViewById(R.id.when_radio_group);
        setOnClickListener(settingAction);
        ((RadioButton) whenRadioGroup.getChildAt(0)).setChecked(true);
    }

    @Override
    protected void initData() {
        mLinkageBean = LinkageDataHolder.getLinkageDataNew();
        if(mLinkageCondition == null){
            deviceName = getString("device_name");
            mLinkageCondition = new LinkageNewBean.LinkageDeviceCondition();
            mLinkageCondition.setActionTypeId(1);
            mLinkageCondition.setOperatorTypeId(1);
            mLinkageCondition.setCompareTypeId(1);
            mLinkageCondition.setConditionTypeId(5);
            mLinkageCondition.setAreaTypeId(getBoolean("is_indoor") ? 1 : 2);
            mLinkageCondition.setAreaCode(getString("room_serial_no"));
            mLinkageCondition.setAreaName(getString("floor_room_name"));
            mLinkageCondition.setDeviceSerialNo(getString("device_serial_no"));
            mLinkageCondition.setBeginValue(1);
            mLinkageCondition.setEndValue(1);
            mLinkageCondition.setSort(mLinkageBean.getConditions().indexOf(mLinkageCondition) + 1);
            mLinkageCondition.setIcon("icon_intelligent_environment_pm25");
            mLinkageCondition.setDescription("空气质量设置");
            mLinkageCondition.setStateName("ari");
        }
        whenRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.type_excellent:
                        mLinkageCondition.setBeginValue(1);
                        tvAirQuality.setText(getString(R.string.effective_when_air_quality_holder, getString(R.string.excellent)));
                        break;
                    case R.id.type_good:
                        mLinkageCondition.setBeginValue(2);
                        tvAirQuality.setText(getString(R.string.effective_when_air_quality_holder, getString(R.string.good)));
                        break;
                    case R.id.type_poor:
                        mLinkageCondition.setBeginValue(3);
                        tvAirQuality.setText(getString(R.string.effective_when_air_quality_holder, getString(R.string.poor)));
                        break;
                }
            }
        });
        updateView();
    }

    private void updateView() {
        if (getBoolean("is_indoor")) {
            setTitle(R.string.indoor_air_quality);
            DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(mLinkageCondition.getDeviceSerialNo());
            if(deviceBean != null){
                deviceName = deviceBean.getName();
            }
            settingReferenceArea.setEnabled(false);
            settingReferenceArea.setRightDrawable(null);
            settingDataSourceDevice.setVisibility(View.VISIBLE);
            settingDataSourceDevice.setRightText(deviceName);
            settingLinkageAction.setRightText("处于");
            setOnClickListener(settingDataSourceDevice);
            List<DeviceBean> data = LLDeviceDBManager.getInstance(getContext()).getRoomEnvironmentDevices(mLinkageCondition.getAreaCode(), DeviceBean.ENVIRONMENT_TYPE_AIR_QUALITY);
            if(data.size() > 1){
                settingDataSourceDevice.setRightDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_list_next_normal));
                settingDataSourceDevice.setEnabled(true);
            }else{
                settingDataSourceDevice.setRightDrawable(null);
                settingDataSourceDevice.setEnabled(false);
            }
        } else {
            setTitle(R.string.outdoor_air_quality);
            settingReferenceArea.setRightDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_list_next_normal));
            if(TextUtils.isEmpty(mLinkageCondition.getAreaName())){
                mLinkageCondition.setLongitude(AppApplication.getInstance().getCurHouseInfo().getLongitude());
                mLinkageCondition.setLatitude(AppApplication.getInstance().getCurHouseInfo().getLatitude());
                mLinkageCondition.setAreaName(AppApplication.getInstance().getCurHouseInfo().getProvince() + " " + AppApplication.getInstance().getCurHouseInfo().getCity() + " " + AppApplication.getInstance().getCurHouseInfo().getDistrict());
                mLinkageCondition.setAreaCode(AppApplication.getInstance().getCurHouseInfo().getDistrictId());
            }
            setOnClickListener(settingReferenceArea);
            settingDataSourceDevice.setVisibility(View.GONE);
        }
        settingReferenceArea.setRightText(mLinkageCondition.getAreaName());
        switch ((int) mLinkageCondition.getBeginValue()) {
            case 1:
                ((RadioButton) whenRadioGroup.getChildAt(0)).setChecked(true);
                break;
            case 2:
                ((RadioButton) whenRadioGroup.getChildAt(2)).setChecked(true);
                break;
            case 3:
                ((RadioButton) whenRadioGroup.getChildAt(4)).setChecked(true);
                break;
        }
        settingAction.setRightText(mLinkageCondition.getActionTypeId() == 1 ? R.string.linkage_action_become : R.string.linkage_action_keep);
    }

    @Override
    public void onRightClick(View view) {
        if (TextUtils.isEmpty(mLinkageCondition.getAreaName())) {
            toast(R.string.please_select_reference_area_hint);
            return;
        }
        //当前联动空，才去
        if (getBoolean("isAdd")) {
            mLinkageBean.getConditions().add(mLinkageCondition);
        }else{
            int position = getInt("position");
            mLinkageBean.getConditions().remove(position);
            mLinkageBean.getConditions().add(position,mLinkageCondition);
        }
        startActivity_SingleTask(EditLinkageActivityNew.class);
        finish();
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.setting_action:
                showBottomListDialog();
                break;
            case R.id.setting_reference_area:
//                showBottomDistrictDialog();
                intent = new Intent(getContext(), LocationActivity.class);
                LocationData locationData = new LocationData();
                if (mLinkageCondition.getLongitude() > 0 && mLinkageCondition.getLatitude() > 0) {
                    locationData.location = mLinkageCondition.getLongitude() + ":" + mLinkageCondition.getLatitude();
                } else {
                    if (AppApplication.getInstance().getCurHouseInfo() != null) {
                        locationData.location = AppApplication.getInstance().getCurHouseInfo().getLongitude() + ":" + AppApplication.getInstance().getCurHouseInfo().getLatitude();
                    }
                }
                LocationActivity.startForResult(this, locationData, 1, LocationActivity.LOCATION_REQUEST_CODE);
                break;
            case R.id.setting_data_source_device:
                intent = new Intent(this, DataSourceDeviceActivity.class);
                intent.putExtra("device_serial_no", mLinkageCondition.getDeviceSerialNo());
                intent.putExtra("room_serial_no", mLinkageCondition.getAreaCode());
                intent.putExtra("environment_type", DeviceBean.ENVIRONMENT_TYPE_AIR_QUALITY);
                startActivityForResult(intent, new OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode, @Nullable Intent data) {
                        if(resultCode == RESULT_OK){
                            mLinkageCondition.setAreaName(data.getStringExtra("floor_room_name"));
                            mLinkageCondition.setAreaCode(data.getStringExtra("room_serial_no"));
                            deviceName = data.getStringExtra("device_name");
                            mLinkageCondition.setDeviceSerialNo(data.getStringExtra("device_serial_no"));
                            settingReferenceArea.setRightText(mLinkageCondition.getAreaName());
                            settingDataSourceDevice.setRightText(deviceName);
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if (requestCode == LocationActivity.LOCATION_REQUEST_CODE) {
                LocationData locationData = (LocationData) data.getSerializableExtra("DATA");
                mLinkageCondition.setLongitude(locationData.longitude);
                mLinkageCondition.setLatitude(locationData.latitude);
                mLinkageCondition.setAreaName(locationData.province + " " + locationData.city + " " + locationData.district);
                mLinkageCondition.setAreaCode(locationData.provinceId + locationData.cityId + locationData.districtId);
                settingReferenceArea.setRightText(mLinkageCondition.getAreaName());
            }
        }
    }

    private void showBottomListDialog() {
        if (mBottomActionDialog == null) {
            mBottomActionDialog = new BottomListDialog(this);
            mBottomActionDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add("变为");
            data.add("处于");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    mLinkageCondition.setActionTypeId(position + 1);
                    settingAction.setRightText(mLinkageCondition.getActionTypeId() == 1 ? R.string.linkage_action_become : R.string.linkage_action_keep);
                    mBottomActionDialog.dismiss();
                }
            });
            mBottomActionDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomActionDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomActionDialog.getAdapter();
        listLabelAdapter.setSelected("");
        mBottomActionDialog.show();
    }
}